/**
 * industry控制器
 *
 * @author sxf
 * @email sxf02615@163.com
 * @date 2025/1/15
 */
package com.sxf.crm.controller;


import com.sxf.crm.dto.IndustryDTO;
import com.sxf.crm.entity.Industry;
import com.sxf.crm.repository.IndustryRepository;

import lombok.RequiredArgsConstructor;

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/industries")
@RequiredArgsConstructor
public class IndustryController {

    private final IndustryRepository industryRepository;

    @PreAuthorize("hasAuthority('industry:list')")
    @GetMapping
    public ResponseEntity<List<IndustryDTO>> getAllIndustries() {
        List<Industry> industries = industryRepository.findAll();
        List<IndustryDTO> dtos = industries.stream()
                .map(IndustryDTO::fromEntity)
                .collect(Collectors.toList());
        return ResponseEntity.ok(dtos);
    }

    @PreAuthorize("hasAuthority('industry:list')")
    @GetMapping("/tree")
    public ResponseEntity<List<IndustryDTO>> getIndustryTree() {
        List<Industry> rootIndustries = industryRepository.findAllRootIndustries();
        List<IndustryDTO> dtos = rootIndustries.stream()
                .map(IndustryDTO::fromEntity)
                .collect(Collectors.toList());
        return ResponseEntity.ok(dtos);
    }

    @PreAuthorize("hasAuthority('industry:list')")
    @GetMapping("/{id}")
    public ResponseEntity<IndustryDTO> getIndustry(@PathVariable Long id) {
        return industryRepository.findById(id)
                .map(industry -> ResponseEntity.ok(IndustryDTO.fromEntity(industry)))
                .orElse(ResponseEntity.notFound().build());
    }

    @PreAuthorize("hasAuthority('industry:list')")
    @GetMapping("/{id}/children")
    public ResponseEntity<List<IndustryDTO>> getIndustryChildren(@PathVariable Long id) {
        List<Industry> children = industryRepository.findChildrenByParentId(id);
        List<IndustryDTO> dtos = children.stream()
                .map(IndustryDTO::fromEntity)
                .collect(Collectors.toList());
        return ResponseEntity.ok(dtos);
    }

    @PreAuthorize("hasAuthority('industry:list')")
    @GetMapping("/search")
    public ResponseEntity<List<IndustryDTO>> searchIndustries(@RequestParam String keyword) {
        List<Industry> industries = industryRepository.findByPathStartingWith(keyword);
        List<IndustryDTO> dtos = industries.stream()
                .map(IndustryDTO::fromEntity)
                .collect(Collectors.toList());
        return ResponseEntity.ok(dtos);
    }
} 